import { Command } from "commander";
import fs from "fs";
import { CreateService } from "./CreateService";
import { ConfigType } from "./config.type";

export type CreateArgs = {
    config: ConfigType;
    exportPath: string;
};

const parse = (args: any): CreateArgs | undefined => {
    if (args.configPath && typeof args.configPath === "string" && args.exportPath && typeof args.exportPath === "string") {
        const config = JSON.parse(fs.readFileSync(args.configPath).toString());
        return {
            config,
            exportPath: args.exportPath,
        };
    }
    return undefined;
};

const program = new Command("create")
    .option("-c, --configPath <value>", "The path of the config json file")
    .option("-e, --export-path <value>", "The path to export the node assets")
    .addHelpText(
        "afterAll",
        `Config file must have the following format: 
    ${JSON.stringify(
        {
            blockchain: {
                chainId: "1440002",
                nodes: 3,
            },
            bridge: {
                xrplRpc: "wss://sidechain-net1.devnet.rippletest.net",
                xrplSeed: "***",
                minCreateAmount: 50,
                minRewardAmount: 1,
                quorum: 1,
                witnesses: [
                    {
                        type: "aws",
                        evmAddress: "0x96329A50d10a3F69311E4f4E108672926c51c474",
                        xrpAddress: "rpSspP5yYyomcSrgsohyKMCnu5oJsTMkYP",
                        region: "eu-west-1",
                        accessKey: "****",
                        secretAccessKey: "****",
                        keyId: "****",
                    },
                ],
            },
            explorer: {
                disable: false,
            },
        },
        undefined,
        4,
    )}`,
    )
    .action(async (args) => {
        const parsedArgs = parse(args);
        if (parsedArgs) {
            const createService = new CreateService(parsedArgs.config, parsedArgs.exportPath);
            try {
                await createService.create();
            } catch (error) {
                console.log(error);
                process.exit(1);
            }
            process.exit(0);
        } else {
            program.help();
            process.exit(1);
        }
    });
export default program;
